﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Dropthings.Widget.Framework;
using Microsoft.Reporting.WebForms;
using System.Xml.Linq;
using System.Data;
using Dropthings.Business.Facade;
using Dropthings.Business.Facade.Context;

public partial class Widgets_ReportViewWidget : System.Web.UI.UserControl, IWidget
{
    #region Fields
    private IWidgetHost _Host;

    private XElement _State;
    private XElement State
    {
        get
        {
            if (_State == null)
            {
                string stateXml = this._Host.GetState();
                if (string.IsNullOrEmpty(stateXml))
                {
                    _State = new XElement("state",
                        new XElement("year", DateTime.Now.Year.ToString()),
                        new XElement("month", DateTime.Now.Month.ToString()),
                        new XElement("orgnaziationCode", ""));
                }
                else
                {
                    _State = XElement.Parse(stateXml);
                }
            }
            return _State;
        }
    }


    public int ShowYear
    {
        get { return State.Element("year") == null ? DateTime.Now.Year : int.Parse(State.Element("year").Value); }
        set
        {
            if (State.Element("year") == null)
                State.Add(new XElement("year", value));
            else
                State.Element("year").Value = value.ToString();
        }
    }
    public string ShowBuildingCode
    {
        get { return State.Element("orgnaziationCode") == null ? "" : State.Element("orgnaziationCode").Value; }
        set
        {
            if (State.Element("orgnaziationCode") == null)
                State.Add(new XElement("orgnaziationCode", value));
            else
                State.Element("orgnaziationCode").Value = value;
        }
    }
    public int ShowMonth
    {
        get { return (State.Element("month") == null || State.Element("month").Value == "0") ? DateTime.Now.Month : int.Parse(State.Element("month").Value); }
        set
        {
            if (State.Element("month") == null)
                State.Add(new XElement("month", value));
            else
                State.Element("month").Value = value.ToString();
        }

    }

    #endregion Fields

    #region 实现IWidget接口
    void IWidget.Closed()
    {

    }

    void IWidget.Collasped()
    {

    }

    void IWidget.Expanded()
    {

    }

    void IWidget.HideSettings(bool userClicked)
    {
        SettingsPanel.Visible = false;
        this.ShowYear = int.Parse(YearDropDownList.SelectedValue);
        this.ShowMonth = int.Parse(MonthDropDownList.SelectedValue);
        this.ShowBuildingCode = BuildingDropDownList.SelectedValue;
        this.SaveState();
        RefreshReport();

    }

    void IWidget.Init(IWidgetHost host)
    {
        this._Host = host;
    }

    void IWidget.Maximized()
    {

    }

    void IWidget.Restored()
    {

    }
    private void SaveState()
    {
        var xml = this.State.Xml();
        this._Host.SaveState(xml);
        this._State = null;
    }

    void IWidget.ShowSettings(bool userClicked)
    {
        SettingsPanel.Visible = true;
        if (userClicked)
        {
            YearDropDownList.SelectedIndex = -1;
            YearDropDownList.Items.FindByText(this.ShowYear.ToString()).Selected = true;
            MonthDropDownList.SelectedIndex = -1;
            MonthDropDownList.Items.FindByValue(this.ShowMonth.ToString()).Selected = true;
            BuildingDropDownList.SelectedIndex = -1;
            if (BuildingDropDownList.Items.FindByValue(this.ShowBuildingCode) != null)
                BuildingDropDownList.Items.FindByValue(this.ShowBuildingCode).Selected = true;
        }
    }

    void IEventListener.AcceptEvent(object sender, EventArgs e)
    {

    }
    #endregion

    protected void SaveSettings_Click(object sender, EventArgs e)
    {
        _Host.HideSettings(true);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (YearDropDownList.Items.Count == 0)
        {
            for (int i = 2000; i <= DateTime.Now.Year; i++)
            {
                YearDropDownList.Items.Add(new ListItem(i.ToString()));
            }
        }

        if (BuildingDropDownList.Items.Count == 0)
        {
            Dictionary<string, string> allBuildings = getAllBuildings();
            foreach (string key in allBuildings.Keys)
            {
                ListItem item = new ListItem();
                item.Text = allBuildings[key];
                item.Value = key;
                BuildingDropDownList.Items.Add(item);
            }
            if (BuildingDropDownList.Items.Count > 0)
                this.ShowBuildingCode = BuildingDropDownList.Items[0].Value;
        }
        if (!IsPostBack)
        {
            this.ReportViewer1.Load += new EventHandler(ReportViewer1_Load);
        }
    }

    void ReportViewer1_Load(object sender, EventArgs e)
    {
        RefreshReport();
    }

    void RefreshReport()
    {
        SetParameters();
        this.ObjectDataSource1.SelectParameters[0].DefaultValue = ShowBuildingCode;
        this.ObjectDataSource1.SelectParameters[1].DefaultValue = ShowYear.ToString();
        this.ObjectDataSource1.SelectParameters[2].DefaultValue = ShowMonth.ToString();
        this.ObjectDataSource2.SelectParameters[0].DefaultValue = ShowBuildingCode;
        this.ObjectDataSource2.SelectParameters[1].DefaultValue = ShowYear.ToString();
        this.ObjectDataSource2.SelectParameters[2].DefaultValue = ShowMonth.ToString();
        this.ObjectDataSource3.SelectParameters[0].DefaultValue = ShowBuildingCode;
        this.ObjectDataSource3.SelectParameters[1].DefaultValue = ShowYear.ToString();
        this.ObjectDataSource3.SelectParameters[2].DefaultValue = ShowMonth.ToString();
        this.ReportViewer1.LocalReport.Refresh();
    }

    private void SetParameters()
    {
        DataSet buildingInfoDS=GetBuildingInfo();
        string[] basis = GetBasis();
        if (buildingInfoDS != null && buildingInfoDS.Tables.Count > 0 && buildingInfoDS.Tables[0].Rows.Count > 0)
        {
            ReportParameter buildingNameParameter = new ReportParameter("BuildingName", buildingInfoDS.Tables[0].Rows[0]["OrganizeName"].ToString());
            ReportParameter BuildingAddressParameter = new ReportParameter("BuildingAddress", buildingInfoDS.Tables[0].Rows[0]["OrganizeAddress"].ToString());
            ReportParameter BuildingPhoneParameter = new ReportParameter("BuildingPhone", buildingInfoDS.Tables[0].Rows[0]["PhoneNum"].ToString());
            ReportParameter BuildingCodeParameter = new ReportParameter("BuildingCode", buildingInfoDS.Tables[0].Rows[0]["OrganizeCode"].ToString());
            ReportParameter BuildingZipParameter = new ReportParameter("BuildingZip", buildingInfoDS.Tables[0].Rows[0]["Postalcode"].ToString());
            ReportParameter BuildingEmailParameter = new ReportParameter("BuildingEmail", buildingInfoDS.Tables[0].Rows[0]["EMailBox"].ToString());
            ReportParameter BuildingFaxParameter = new ReportParameter("BuildingFax", buildingInfoDS.Tables[0].Rows[0]["FaxNum"].ToString());
            ReportParameter MonthParameter = new ReportParameter("Month", ShowMonth.ToString());
            ReportParameter YearBasisParameter = new ReportParameter("YearBasis", basis[0]);
            ReportParameter MonthBasisParameter = new ReportParameter("MonthBasis", basis[1]);
            this.ReportViewer1.LocalReport.SetParameters(new ReportParameter[] 
            { buildingNameParameter, BuildingAddressParameter, BuildingPhoneParameter, 
                BuildingCodeParameter, BuildingZipParameter, BuildingEmailParameter, 
                BuildingFaxParameter,MonthParameter,YearBasisParameter,MonthBasisParameter });
        }
        
    }
    private DataSet GetBuildingInfo()
    {
        using (Facade facade = new Facade(AppContext.GetContext(Context)))
        {
            DataSet ds = facade.GetOrganizeBaseInfo(ShowBuildingCode);
            return ds;
        }
    }

    private string[] GetBasis()
    {
        using (Facade facade = new Facade(AppContext.GetContext(Context)))
        {
            string[] ds = facade.EcBasisInMonth(ShowYear,ShowMonth,ShowBuildingCode);
            return ds;
        }
    }

    private Dictionary<string, string> getAllBuildings()
    {
        using (Facade facade = new Facade(AppContext.GetContext(Context)))
        {
            Dictionary<string, string> allBuildings = new Dictionary<string, string>();
            DataSet ds = facade.GetOrganizeBaseInfo();
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    string name = Convert.ToString(dr["OrganizeName"]);
                    string key = Convert.ToString(dr["OrganizeIdentify"]);
                    allBuildings.Add(key, name);
                }
            }
            return allBuildings;
        }
    }
    


    
}